
var drawProgress = require("../../js/drawcircle.js");
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bid:'',
    usid:'',

    cur_year:'', //显示的年
    cur_month: '', //显示的月
    weeks_ch:['日', '一', '二', '三', '四', '五', '六'],
    hasEmptyGrid:false,
    todayIndex:'', 
    defalut: '../../images/score_stars_icon_yellow.png',//默认图片

    bookplan:{},//读书计划
    logs: [],//读书记录
    showlog:{},//展示当天的读书记录
    oneday:{},
    oneweek:'',//选中的天为星期几
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var usid = wx.getStorageSync('usid');
    if (usid == "") {
      wx.redirectTo({
        url: '../../pages/index/index'
      })
    } else { 
      this.setData({
        bid: options.bid,
        usid: usid
      })
    }
    this.setNowDate();

    //查询本书打卡情况
    this.getBookreadLog();
  },


  //设置当前日期与日历
  setNowDate: function () {
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const todayIndex = date.getDate() - 1;
    var weeks_ch = this.data.weeks_ch;
  
    const oneday={
      text: date.getDate(),
      result: false,
      progress: 'defalut',
      index: date.getDate()
    }
    this.setData({
      cur_year: cur_year,
      cur_month: cur_month,
      oneday: oneday,
      oneweek: weeks_ch[new Date().getDay()],
      todayIndex,
    })

    this.calculateEmptyGrids(cur_year, cur_month);
    this.calculateDays(cur_year, cur_month);
 
  },

  //获取当月的1号从星期几开始
  calculateEmptyGrids(year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
  },

  //获取当月的1号从星期几开始
  getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },
  //循环获取当月日期
  calculateDays(year, month) {
    let days = [];
    const thisMonthDays = this.getThisMonthDays(year, month);
    //当天的年月日
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    var todayIndex = this.data.todayIndex;
    var index = parseInt(todayIndex) + 1;

    for (let i = 1; i <= thisMonthDays; i++) {
      var today=false;
      if (parseInt(cur_year) == parseInt(year) && parseInt(cur_month) == parseInt(month) && parseInt(i) == parseInt(index)){
        today=true;
      }
      var d={
        text:i,
        result:false,
        progress:'defalut',
        today: today,
        index:i,
      }
      days.push(d);
    }
    this.setData({
      days
    });
  },
  //获取当月月份
  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate();
  },

  //切换月份
  handleCalendar(e) {
    const handle = e.currentTarget.dataset.handle;
    const cur_year = this.data.cur_year;
    const cur_month = this.data.cur_month;
    if (handle === 'prev') {
      let newMonth = cur_month - 1;
      let newYear = cur_year;
      if (newMonth < 1) {
        newYear = cur_year - 1;
        newMonth = 12;
      }

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);
    
      this.setData({
        cur_year: newYear,
        cur_month: newMonth
      })
      this.calculatePlanDays();
    } else {
      let newMonth = cur_month + 1;
      let newYear = cur_year;
      if (newMonth > 12) {
        newYear = cur_year + 1;
        newMonth = 1;
      }

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);
      this.setData({
        cur_year: newYear,
        cur_month: newMonth
      })
      this.calculatePlanDays();
    }
  },


  getBookreadLog(e) {
    var that = this;
    var bid = that.data.bid;
    var usid = that.data.usid;
    app.wxget({
      url: 'wdsj/getBookreadLog.html',
      data: {
        bid: bid,
        usid: usid
      },
      success: function (res) {
        var logs = res.data.logs;
        if (logs){ 
          that.setData({
            logs: logs
          })
        }

        that.setData({
          bookplan: {
            PLANID: res.data.PLANID,
            USID: res.data.USID,
            MINPAGE: res.data.MINPAGE,
            USERNAME: res.data.USERNAME,
            ADDTIME: res.data.ADDTIME,
            JD: res.data.JD,
            BOOKNAME: res.data.BOOKNAME,
            TOTALPAGE: res.data.TOTALPAGE,
            MINNUM: res.data.MINNUM,
            NJ: res.data.NJ,
            BJ: res.data.BJ,
            AUTHOR: res.data.AUTHOR,
            REASON: res.data.REASON,
            RECOMMENDOR: res.data.RECOMMENDOR,
            SH: res.data.SH,
            BOOKJJ: res.data.BOOKJJ,
            AUTHORJJ: res.data.AUTHORJJ,
            BOOKXX: res.data.BOOKXX,
            TJLY: res.data.TJLY,
            PAGENUM: res.data.PAGENUM,
          }
        });
        wx.setNavigationBarTitle({
          title: "《" + res.data.BOOKNAME +"》"
        }) 
        //x坐标，y坐标，r半径，计数器最大值60,对应 2
        drawProgress.drawProgress(75, 75, 65, 0.6 * parseInt(res.data.JD));
        that.calculatePlanDays();
      }
    })
  },



  calculatePlanDays() {
    var days=this.data.days;
    var cur_year = this.data.cur_year;
    var cur_month = this.data.cur_month;
    var bookplan = this.data.bookplan;
    var logs = this.data.logs;
    //今天的号数
    var todayIndex = this.data.todayIndex;
    var today = parseInt(todayIndex) + 1;

    for (var i = 0; i < days.length;i++){
      var di = days[i];
      for (var j = 0; j < logs.length; j++) {
        var logj = logs[j];
        //同一天
        if ((parseInt(cur_year) == parseInt(logj.YEAR)) && (parseInt(cur_month) == parseInt(logj.MONTH))){
          if ((parseInt(di.text) == parseInt(logj.DAY))) {
            if (j == 0) {
              days[i].text = "开始";
              days[i].progress = "start";
            } else if (j == (logs.length - 1)) {
              if (bookplan.JD=='100'){
                days[i].text = "结束";
                days[i].progress = "end";
              }else{
                days[i].progress = "ing";
              }
            } else {
              days[i].progress = "ing";
            }
            //如果阅读量大于了最小读书量
            if (logj.PAGENUM >= bookplan.MINNUM) {
              days[i].result = true;
            } else {
              days[i].result = false;
            }
            //如果是今天
            if (parseInt(di.index) == parseInt(today) ) {
              this.setData({
                showlog: logj,
                oneday: di
              })
              days[i].today=true;
            } 
          }
        }
        //同一天
      }
    }

    this.setData({
      days: days
    })
  },
 

  dateSelectAction(e) {
    var day = e.currentTarget.dataset.day;
    var index = e.currentTarget.dataset.index;
    var cur_year = this.data.cur_year;
    var cur_month = this.data.cur_month;
    var logs = this.data.logs;
    for (var j = 0; j < logs.length; j++) {
      var logj = logs[j];
      //同一天
      if ((parseInt(cur_year) == parseInt(logj.YEAR)) && (parseInt(cur_month) == parseInt(logj.MONTH))) {
        if ((parseInt(day) == parseInt(logj.DAY))) {   
          this.setData({
            showlog: logj
          })
          
        }
      }
      //同一天
    }
   
    var days=this.data.days;
    //获取星期几
    var weeks_ch = this.data.weeks_ch;
    var da = cur_year + "-" + cur_month + "-" + day;
    var week = weeks_ch[new Date(da).getDay()];
    //当前日期为被选中状态
    for (var k = 0; k < days.length;k++){
      days[k].today=false;
    }
    days[index].today = true;

    this.setData({
      oneday: days[index],
      days: days,
      oneweek: week
    })
  },



  //预览阅读剪影图片
  viewimage: function (e) {
    var that = this;
    var cuindex = e.target.dataset.index;
    var showlog = that.data.showlog;
    var pics = showlog.pics;
    var urls=[];
    for (var i = 0; i < pics.length;i++){
      urls.push(pics[i].PICURL);
    }
    wx.previewImage({
      current: urls[cuindex], // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },



  //预览好词好句好段图片
  viewhchjhdimage: function (e) {
    var that = this;
    var cuindex = e.target.dataset.index;
    var showlog = that.data.showlog;
    var lishchjhd = showlog.lishchjhd;
    var urls = [];
    for (var i = 0; i < lishchjhd.length; i++) {
      urls.push(lishchjhd[i].PICURL);
    }
    wx.previewImage({
      current: urls[cuindex], // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  //预览章节读后感图片
  viewzjdhgimage: function (e) {
    var that = this;
    var cuindex = e.target.dataset.index;
    var showlog = that.data.showlog;
    var liszjdhg = showlog.liszjdhg;
    var urls = [];
    for (var i = 0; i < liszjdhg.length; i++) {
      urls.push(liszjdhg[i].PICURL);
    }
    wx.previewImage({
      current: urls[cuindex], // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  


  wydk() {
    var bid = this.data.bid;
    //查询用户当天是否已经打卡 
    var that = this;
    var bid = that.data.bid;
    var usid = that.data.usid;
    app.wxget({
      url: 'wdsj/getBookreadLogToday.html',
      data: {
        bid: bid,
        usid: usid
      },
      success: function (res) {
        if (res.data){
          wx.redirectTo({
            url: '../../pages/bookwydk/bookwydk?bid=' + bid
          })
        }else{
          wx.showModal({
            title: '友情提示',
            content: '你今天已经打卡成功了，不需要重复打卡!',
            showCancel: !1,
          })
          return;
        }
      }
    })
  },

})